package com.imdroid.web.listener;

import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServlet;

import com.imdroid.notification.ClientNotConnectedException;
import com.imdroid.notification.ClientPool;
import com.imdroid.notification.NPing;
import com.sun.grizzly.comet.CometContext;

@WebListener
public class HeartBeatListener extends HttpServlet implements
		ServletContextListener {
	/**
	 * The serial version uuid
	 */
	private static final long serialVersionUID = -7624139798999778724L;
	/**
	 * The receiver
	 */
	private Thread thread;
	/**
	 * the flag to indicate if it is runing
	 */
	private boolean runing = true;

	private final static int HEAT_BEAT_INTERVAL = 30 * 1000;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.ServletContextListener#contextInitialized(javax.servlet
	 * .ServletContextEvent)
	 */
	public void contextInitialized(ServletContextEvent sce) {
		try {
			thread = new Thread(new HeartBeatRunner());
			thread.start();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.
	 * ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent sce) {
		runing = false;
		thread = null;
	}

	class HeartBeatRunner implements Runnable {

		/*
		 * (non-Javadoc)
		 * 
		 * @see java.lang.Runnable#run()
		 */
		public void run() {
			while (runing) {
				try {
					Map<Integer, CometContext> clients = ClientPool
							.getInstance().getClients();
					if (clients != null && clients.size() > 0) {
						Set<Integer> userIds = clients.keySet();

						for (int userId : userIds) {
							NPing empty = new NPing();
							try {
								empty.send(userId);
							} catch (ClientNotConnectedException e) {
								e.printStackTrace();
							}
						}
					}

					Thread.sleep(HEAT_BEAT_INTERVAL);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
